package com.shh.aiojbackendserver.rabbmitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.shh.aiojbackendserver.constant.RabbmitMqConstant.*;

/**
 * 初始化消息队列
 */
@Slf4j
public class InitRabbitMq{

    public static void doInit() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            // 创建主交换机和队列
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");


            // 创建死信交换机和队列
            channel.exchangeDeclare(DLX_EXCHANGE_NAME, "direct");
            channel.queueDeclare(DLX_QUEUE_NAME, true, false, false, null);
            channel.queueBind(DLX_QUEUE_NAME, DLX_EXCHANGE_NAME, DLX_ROUTING_KEY);

            // 创建主队列并绑定死信交换机
            Map<String, Object> args = new HashMap<>();
            args.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
            args.put("x-dead-letter-routing-key", DLX_ROUTING_KEY);
            // 可选：设置消息过期时间（毫秒），如果不需要可以去掉
            // args.put("x-message-ttl", 60000);

            // 创建队列，随机分配一个队列名称
            channel.queueDeclare(QUEUE_NAME, true, false, false, args);
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

            log.info("消息队列启动成功");
        } catch (Exception e) {
            log.error("消息队列启动失败");
        }
    }

    public static void main(String[] args) {
        doInit();
    }
}
